#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <stdio.h>
#include <stdlib.h>

Atom get_atom(Display *display, const char *atom_name) {
    return XInternAtom(display, atom_name, False);
}

long get_window_property(Display *display, Window window, Atom property, Atom type) {
    Atom actual_type;
    int actual_format;
    unsigned long nitems;
    unsigned long bytes_after;
    unsigned char *prop_return;

    if (XGetWindowProperty(display, window, property, 0L, (~0L), False, type,
                           &actual_type, &actual_format, &nitems, &bytes_after, &prop_return) == Success) {
        if (prop_return != NULL) {
            printf("prop_return:%p, actual_type:%lu, actual_format:%d, nitems:%lu, bytes_after:%lu\n", prop_return, actual_type, actual_format, nitems, bytes_after);
            long result = *(long *)prop_return;
            auto p = reinterpret_cast<Atom*>(prop_return);
            for(int i = 0; i<nitems; i++)
            {
                if(i==0)
                {
                    printf("Sate:");
                }
                printf(" %lu", p[i]);
                if(i+1 < nitems)
                {
                    printf(" |");
                }
            }
            putchar('\n');


            XFree(prop_return);
            return result;
        }
    }
    return 0;
}

int is_maximized(Display *display, Window window) {
    Atom net_wm_state = get_atom(display, "_NET_WM_STATE");
    Atom net_wm_state_maximized_horz = get_atom(display, "_NET_WM_STATE_MAXIMIZED_HORZ");
    Atom net_wm_state_maximized_vert = get_atom(display, "_NET_WM_STATE_MAXIMIZED_VERT");

    long state = get_window_property(display, window, net_wm_state, XA_ATOM);
    printf("_NET_WM_STATE_MAXIMIZED_HORZ:%lu\n", net_wm_state_maximized_horz);
    printf("_NET_WM_STATE_MAXIMIZED_VERT:%lu\n", net_wm_state_maximized_vert);

    // Check if the window has both maximized horizontal and vertical states
    return (state & net_wm_state_maximized_horz && state & net_wm_state_maximized_vert);
}

int main(int argc, char *argv[]) {
    Display *display = XOpenDisplay(NULL);
    if (!display) {
        fprintf(stderr, "Cannot open display\n");
        exit(1);
    }

    // You need to know the window ID you want to check
    // For demonstration, let's assume we have a window ID
    Window target_window; // Replace with your actual window ID
    sscanf(argv[1], "%lx", &target_window);

    if (is_maximized(display, target_window)) {
        printf("Window is maximized.\n");
    } else {
        printf("Window is not maximized.\n");
    }

    XCloseDisplay(display);
    return 0;
}


